// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  //拿资料
  let {avatar}=event
  let openid=wxContext.OPENID
  let db=cloud.database()
  //检查用户是否存在
  let res=await db.collection('user').where({openid}).get()
  let userInfo=null
  if(res.data.length!=0){
    userInfo=res.data[0]
  }else{
    // 新用户，生成随机昵称并创建记录
    let name1 = Math.round(Math.random() * 10000 + 20000)
    let name2 = Math.round(Math.random() * 10000 + 20000)
    let name3 = Math.round(Math.random() * 10000 + 20000)
    let nickname = String.fromCharCode(name1) + String.fromCharCode(name2) + String.fromCharCode(name3)
    let res1=await db.collection('user').add({
      data:{
        openid,
        avatar,
        username: nickname,
        gender: '',
        birthday: '',
        email: '',
        created_at: db.serverDate()
      }
    })
    userInfo={
      openid,
      avatar,
      username: nickname,
      gender: '',
      birthday: '',
      email: ''
    }
  }
 
  return {
    event,
    openid: wxContext.OPENID,
    userInfo,
  }
}